package com.jbm.enterapplication.activityhome.view

import android.Manifest
import android.bluetooth.BluetoothAdapter
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.os.Build
import android.os.Handler
import android.os.Message
import android.support.annotation.RequiresApi
import android.support.v7.widget.Toolbar
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import com.jbm.connet.UtlisNetWork
import com.jbm.db.MySqliUtlis
import com.jbm.enterapplication.InterfaceMa
import com.jbm.enterapplication.R
import com.jbm.enterapplication.activity.MainActivity
import com.jbm.enterapplication.activityhome.presenter.Open_Present
import com.jbm.enterapplication.doorjurisd.DoorOpenBlue
import com.jbm.enterapplication.set.UserSet
import com.jbm.enterapplication.sharedprefer.SharedPreActivity
import com.jbm.enterapplication.utlisclass.ExitActivity
import com.jbm.enterapplication.utlisclass.HttpNet
import com.jbm.onehome.common.OHInterface
import com.jbm.onehome.iface.IEGLogCtrl
import kotlinx.android.synthetic.main.activity_open_door.*
import kotlinx.android.synthetic.main.lz_titlehurdle.*
import rx.Observable
import rx.Observer


class OpenDoor : MainActivity(), Open_Door_In, View.OnClickListener,InterfaceMa<IEGLogCtrl>{
     var  result: String?=null

    override fun onSuccess(t: IEGLogCtrl, boolean: Boolean) {//上传开门日志
        HttpNet.getInstans().obsevice(Observable.create(Observable.OnSubscribe <String>{
            obieglog->
           result = OHInterface.getG_server().UploadEGuardLog(t);
            obieglog.onNext(result)

        })).subscribe(object:Observer<String>{
            override fun onError(e: Throwable?) {
            }
            override fun onNext(t: String?) {
                if (t.equals("OK")) {
                    MySqliUtlis.getInstance(this@OpenDoor).DeleteOp();//开门成功后删除日志表的所有数据
                }
            }

            override fun onCompleted() {

            }

        })
    }

    override fun setError(err: IEGLogCtrl, boolean: Boolean) {

    }

    @RequiresApi(Build.VERSION_CODES.M)
    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.imagedoor -> {
                    if (Build.VERSION.SDK_INT >= 23) {
                        val i = checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        if (i == 0) {
                            imagedoor.isEnabled = false
                            HttpNet.getInstans().getLoadImage(this, R.mipmap.kaimenchengg, imagedoor)
                            doorOpenBlue?.OpenDoorGather("FloatWindow", null, application, this, imagedoor);

                        } else {
                            requestPermissions(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 100)
                        }
                    } else {
                        imagedoor.isEnabled = false
                        HttpNet.getInstans().getLoadImage(this, R.mipmap.kaimenchengg, imagedoor)
                        doorOpenBlue?.OpenDoorGather("FloatWindow", null, application, this, imagedoor);

                    }
            }
            R.id.teleft -> {
                finish()


            }
            R.id.toolbar_image -> {

            }


        }
    }

    override fun getView(): Int {
        return R.layout.activity_open_door
    }

    var openpresent: Open_Present? = null
    var doorOpenBlue: DoorOpenBlue? = null
   var shandprefter:SharedPreActivity?=null
     var  network: OpenDoor.MyBroadCase?=null

     var  shanderprefter: SharedPreActivity?=null

    override fun getinit() {
        ExitActivity.getInstanst().addActivity(this)
        openpresent = Open_Present(this, this)
        doorOpenBlue = DoorOpenBlue(this, handerl,this)
       shanderprefter = SharedPreActivity(this)
        openpresent?.getOpenDoorKey()
        HttpNet.getInstans().getLoadImage(this, R.mipmap.dianji, imagedoor)
        imagedoor.setOnClickListener(this)
        teleft.setOnClickListener(this)
        tetitle.text = "专享开门"
        teleft.visibility=View.GONE
        toolbar_image.setOnClickListener(this)
        shandprefter= SharedPreActivity(this)
        to_custro.title=""
        setSupportActionBar(to_custro);

        to_custro.setOnMenuItemClickListener(object : Toolbar.OnMenuItemClickListener {
            override fun onMenuItemClick(item: MenuItem?): Boolean {
                when(item?.itemId){
                    R.id.xiuigaimima->{
                    startActivity(Intent(this@OpenDoor,UserSet::class.java))
                    }
                }
                return true
            }

        });
        setTooth()
        network = MyBroadCase()//监听网络
        val filter = IntentFilter()
        filter.addAction("SOCKCONN")
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
        registerReceiver(network, filter)
    }

     var  _bluetooth: BluetoothAdapter?=null

    private fun setTooth() {
        _bluetooth = BluetoothAdapter.getDefaultAdapter()
        if (_bluetooth == null) {
            return
        }
        if (_bluetooth!!.isEnabled() == false) {
            if (!_bluetooth!!.isEnabled()) {
                val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
                startActivityForResult(enableBtIntent, 1)
            }
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        if (grantResults[0] == 0) {
            imagedoor.isEnabled = false
            HttpNet.getInstans().getLoadImage(this, R.mipmap.kaimenchengg, imagedoor)
            doorOpenBlue?.OpenDoorGather("FloatWindow", null, application, this, imagedoor);
        } else {

        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }






       var handerl=object :Handler(){//更新开门的图片
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            when(msg?.what){
               DoorOpenBlue.SUCESS->{
                   HttpNet.getInstans().getLoadImage(this@OpenDoor, R.mipmap.moren, imagedoor)
                   this.sendEmptyMessageDelayed(3,9000)
                }
                DoorOpenBlue.ERROR->{
                    HttpNet.getInstans().getLoadImage(this@OpenDoor, R.mipmap.dianji, imagedoor)
                    this.sendEmptyMessageDelayed(3,9000)
                    var name=msg.obj as String
                    if(name!=null){
                        Toast.makeText(this@OpenDoor,name,Toast.LENGTH_SHORT).show()}
                }
               3->{
                   imagedoor.isEnabled = true
                   HttpNet.getInstans().getLoadImage(this@OpenDoor, R.mipmap.dianji, imagedoor)
                }
                DoorOpenBlue.ERROS->{
                    this.sendEmptyMessageDelayed(3,9000)
                    imagedoor.isEnabled = true
                    HttpNet.getInstans().getLoadImage(this@OpenDoor, R.mipmap.dianji, imagedoor)
                }

            }


        }
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        // setIcon()方法设置菜单图标  
           menuInflater.inflate(R.menu.menu,menu)
        return true
    }



inner class MyBroadCase : BroadcastReceiver(){//监听网络  有网上传传开门日志

    override fun onReceive(context: Context?, intent: Intent?) {
        if (intent!!.getAction() == ConnectivityManager.CONNECTIVITY_ACTION) {
            var modework = UtlisNetWork.getnetwokstate(context)
            if (modework == 0 || modework == 1) {
                HttpNet.getInstans().obsevice(Observable.create(Observable.OnSubscribe <String>{OrLogin->
                    if (!shanderprefter?.getIsUser().equals("")){
                        var namepwd = shanderprefter?.getIsUser()
                        var name = namepwd!!.substring(0, namepwd.indexOf(","))
                        var pwd = namepwd!!.substring(namepwd.indexOf(",") + 1, namepwd!!.length)
                        OrLogin.onNext( HttpNet.getInstans().getOhInter().Login(name,pwd))
                    }
                })).subscribe(object :Observer<String>{
                    override fun onNext(t: String?) {
                        if (t == "Login OK") {
                            doorOpenBlue?.getkaimens()
                        } else if (t == "FAILED") {
                            Toast.makeText(this@OpenDoor,"没连接1",Toast.LENGTH_SHORT).show()
                        } else if (t == "request timeout") {
                               Toast.makeText(this@OpenDoor,"超时",Toast.LENGTH_SHORT).show()
                        } else if (t == "Not Connect") {
                            Toast.makeText(this@OpenDoor,"没连接",Toast.LENGTH_SHORT).show()
                        } else {
                        }
                    }
                    override fun onCompleted() {

                    }
                    override fun onError(e: Throwable?) {

                    }

                })




            }  else if (modework==-1){

            }


        }


    }

}

    internal var che: Long = 0
    override fun onBackPressed() {
        if (System.currentTimeMillis() - che > 2000) {
            Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show()
            che = System.currentTimeMillis()
        } else {
            handerl.removeCallbacksAndMessages(null)
            ExitActivity.getInstanst().exitActivity()
            if (network!=null){
                unregisterReceiver(network)
            }

        }
    }
}


